package com.boyunv.interpreter.example02;
/*
 *@description
 *  解释器类
 *@author boyunv
 *@create 2023/9/10 8:46
 *@version 1.0
 */

import java.util.Deque;
import java.util.LinkedList;

public class ExpressionInterpreter {
    
    private Deque<Expression> numbers=new LinkedList<>();
    public  long  interpret(String expression){
        String[] elements = expression.split(" ");
        int length = elements.length;
        for (int i = 0; i < (length+1)/2; ++i) {
            numbers.addLast(new NumberExpression(elements[i]));
            
        }
        
        for (int i = (length+1)/2; i <length ; ++i) {
            String operator = elements[i];
            //判断符号是否为加减乘除
            boolean isValid="+".equals(operator)||"-".equals(operator)||"*".equals(operator)||"/".equals(operator);
            if(!isValid){
                throw new RuntimeException("无效表达式"+expression);
            }
            Expression expression1 = numbers.pollFirst();
            Expression expression2 = numbers.pollFirst();
            Expression result=null;
            
            if("+".equals(operator)){
                result=new PluExpression(expression1,expression2);
            }else  if("-".equals(operator)){
                result=new SubExpression(expression1,expression2);
            } else  if("*".equals(operator)){
                result=new MulExpression(expression1,expression2);
            }else  if("/".equals(operator)){
                result=new DivExpression(expression1,expression2);
            }
            
            long num=result.interpreter();
            numbers.addFirst(new NumberExpression(num));
            
        }
        if(numbers.size()!=1){
            throw new RuntimeException("无效表达式"+expression);
        }
        
        return numbers.pop().interpreter();
    }
}
